<?php

namespace app\shop\controller;

use think\Controller;

class Order extends Controller
{
    //关联查询的意思
    protected $relationSearch = true;
    public function __construct()
    {
        parent::__construct();
        $this->BusinessModel = model('Business.Business');
        $this->AddressModel = model('Business.Address');
        $this->OrderModel = model('Order.Order');
        $this->OrderProductModel = model('Order.Product');
        $this->CartModel = model('Product.Cart');
        $this->BackModel = model('Depot.Back');
        $this->ExpressqueryModel = model('Expressquery');

        $this->business = [];
        if ($this->request->isPost()) {
            $busid = $this->request->param('busid', 0, 'trim');
            $this->business = $this->BusinessModel->find($busid);
            if (!$this->business) {
                $this->error('请先登录');
                exit;
            }
        }
    }

    public function index()
    {
        if ($this->request->isPost()) {
            $status = $this->request->param('status', '', 'trim');
            $page = $this->request->param('page', 1, 'trim');
            $limit = 5;
            // 偏移量
            $start = ($page - 1) * $limit;
            $where = [
                'busid' => $this->business->id,
            ];
            if ($status != '0') {
                $where['status'] = $status;
            }
            // 查询订单商品
            $order = $this->OrderModel
                // ->with(['order', 'products'])
                ->where($where)
                ->order('id asc')
                ->limit($start, $limit)
                ->select();

            // 获取退货表的订单外键-订单编号
            $backcode = $this->BackModel->where($where)->column('ordercode');

            foreach ($order as $item) {
                $product = $this->OrderProductModel->with(['products'])->where(['orderid' => $item['id']])->find();
                $item['products'] = $product['products'];

                $where = [
                    'busid' => $this->business->id,
                ];

                if(in_array($item['code'],$backcode)){
                    $back=$this->BackModel->where("ordercode",$item['code'])->find();
                    // dump($back->toArray());
                    $item['back']=$back;
                }else
                {
                    $item['back']=null;
                }
                // if(!$back)
                // {
                //     echo $item['code'].'无退货';
                //     // exit;
                // }else
                // {
                //     var_dump($back->toArray());
                //     // exit;
                // }


            }
            
            // $orderData=$this->OrderModel->where($where)->select();
            // foreach ($orderData as $i) {
                
            // }
            // halt(collection($order)->toArray());

            // exit;
            // halt(collection($order)->toArray());
            if ($order) {
                $this->success('返回订单商品数据', null, $order);
                exit;
            } else {
                $this->error('暂无更多数据');
                exit;
            }

        }
    }

    // 下订单
    public function add()
    {
        if ($this->request->isPost()) {
            $addrid = $this->request->param('addrid', 0, 'trim');
            $remark = $this->request->param('remark', '', 'trim');
            $cartids = $this->request->param('cartids', 0, 'trim');

            //查询收货地址是否存在
            $where = [
                'busid' => $this->business->id,
                'id' => $addrid
            ];

            $address = $this->AddressModel->where($where)->find();

            if (!$address) {
                $this->error('收货地址不存在');
                exit;
            }

            $where = [
                'busid' => $this->business->id,
                'cart.id' => ['IN', $cartids]
            ];

            //购物车商品记录是否存在
            $cart = $this->CartModel->with(['product'])->where($where)->select();

            if (!$cart) {
                $this->error('购物车记录不存在');
                exit;
            }

            foreach ($cart as $item) {
                //判断商品是否存在
                if ($item['product']['id']) {
                    //获取商品的库存
                    $stock = isset($item['product']['stock']) ? $item['product']['stock'] : 0;

                    //比较
                    if ($item['nums'] > $stock) {
                        $this->error($item['product']['name'] . "库存不足");
                        break;
                    }
                }
            }

            //订单总和
            $total = $this->CartModel->with(['product'])->where($where)->sum('total');

            //判断用户余额是否充足
            $update = bcsub($this->business->money, $total);

            if ($update < 0) {
                $this->error('您的余额不足，请先充值');
                exit;
            }

            //下订单 order order_product 插入
            //商品表减库存 product 更新
            //用户余额更新 business 更新
            // 消费记录插入 business_record 插入
            // 购物车消减 cart 删除

            //加载模型
            $OrderModel = model('Order.Order');
            $OrderProductModel = model('Order.Product');
            $ProductModel = model('Product.Product');
            $BusinessModel = model('Business.Business');
            $RecordModel = model('Business.Record');
            $CartModel = model('Product.Cart');

            // 开启事务
            $OrderModel->startTrans();
            $OrderProductModel->startTrans();
            $ProductModel->startTrans();
            $BusinessModel->startTrans();
            $RecordModel->startTrans();
            $CartModel->startTrans();

            // $OrderData=[];

            // foreach($cart as $item)
            // {
            $code = build_code("SH");

            //订单表
            $OrderData = [
                'code' => $code,
                'busid' => $this->business->id,
                'businessaddrid' => $addrid,
                'amount' => $total,
                'remark' => $remark,
                'status' => '1'
            ];

            //插入
            $OrderStatus = $OrderModel->validate('common/Order/Order')->save($OrderData);

            if ($OrderStatus === FALSE) {
                $this->error($OrderModel->getError());
                exit;
            }

            //获取插入的新增订单ID
            // $orderid = $OrderModel->id;

            //插入订单商品表
            $OrderProductData = [];

            //更新商品库存
            $ProductData = [];

            //循环购物车
            foreach ($cart as $item) {
                $OrderProductData[] = [
                    'orderid' => $OrderModel->id,
                    'proid' => $item['proid'],
                    'pronum' => $item['nums'],
                    'price' => $item['price'],
                    'total' => $item['total']
                ];

                //整理商品库存
                $stock = $item['product']['stock'] ? $item['product']['stock'] : 0;
                $UpdateStock = bcsub($stock, $item['nums']);

                $ProductData[] = [
                    'id' => $item['proid'],
                    'stock' => $UpdateStock
                ];
            }

            //插入多条数据
            $OrderProductStatus = $OrderProductModel->validate('common/Order/Product')->saveAll($OrderProductData);

            if ($OrderProductStatus === FALSE) {
                $OrderModel->rollback();
                $this->error($OrderProductModel->getError());
                exit;
            }

            //更新商品库存
            $ProductStatus = $ProductModel->isUpdate(true)->saveAll($ProductData);

            if ($ProductStatus === FALSE) {
                $OrderProductModel->rollback();
                $OrderModel->rollback();
                $this->error('更新商品库存失败');
                exit;
            }

            //更新用户余额
            $BusinessData = [
                'id' => $this->business->id,
                'money' => $update
            ];

            $BusinessStatus = $BusinessModel->isUpdate(true)->save($BusinessData);

            if ($BusinessStatus === FALSE) {
                $ProductModel->rollback();
                $OrderProductModel->rollback();
                $OrderModel->rollback();
                $this->error('更新用户余额失败');
                exit;
            }

            //消费记录的插入
            $content = "在家居商城上购买商品花费 ￥$total 元";
            $RecordData = [
                'total' => "-$total",
                'busid' => $this->business->id,
                'content' => $content
            ];

            $RecordStatus = $RecordModel->validate('common/Business/Record')->save($RecordData);

            if ($RecordStatus === FALSE) {
                $BusinessModel->rollback();
                $ProductModel->rollback();
                $OrderProductModel->rollback();
                $OrderModel->rollback();
                $this->error('更新用户余额失败');
                exit;
            }

            //删除购物车记录
            $CartStatus = $CartModel->destroy($cartids);

            if ($CartStatus === FALSE) {
                $RecordModel->rollback();
                $BusinessModel->rollback();
                $ProductModel->rollback();
                $OrderProductModel->rollback();
                $OrderModel->rollback();
                $this->error('更新用户余额失败');
                exit;
            }

            if ($OrderStatus === FALSE || $OrderProductStatus === FALSE || $ProductStatus === FALSE || $BusinessStatus === FALSE || $RecordStatus === FALSE || $CartStatus === FALSE) {
                $CartModel->rollback();
                $RecordModel->rollback();
                $BusinessModel->rollback();
                $ProductModel->rollback();
                $OrderProductModel->rollback();
                $OrderModel->rollback();
                $this->error('下单失败');
                exit;
            } else {
                $OrderModel->commit();
                $OrderProductModel->commit();
                $ProductModel->commit();
                $BusinessModel->commit();
                $RecordModel->commit();
                $CartModel->commit();
                $this->success('下单成功，请等待后台发货', '/order/index');
                exit;
            }
        }
    }

    // 订单详情
    public function info()
    {
        if ($this->request->isPost()) {
            $orderid = $this->request->param('orderid', 0, 'trim');
            $where = [
                'order.busid' => $this->business->id,
                'order.id' => $orderid
            ];

            $order = $this->OrderModel->with(['address', 'express'])->where($where)->find();

            if (!$order) {
                $this->error("订单不存在");
                exit;
            }

            $products = $this->OrderProductModel->with(['products'])->where(['orderid' => $order['id']])->select();

            if (!$products) {
                $this->error("订单商品不存在");
                exit;
            }
            $order['product'] = $products;
            $this->success('返回订单商品', null, $order);
            exit;
        }
    }


    // 查看物流
    public function express()
    {
        if ($this->request->isPost()) {
            $orderid = $this->request->param('orderid', 0, 'trim');

            $where = [
                'busid' => $this->business->id,
                'id' => $orderid
            ];

            // 先判断订单是否存在
            $order = $this->OrderModel->where($where)->find();

            if (!$order) {
                $this->error('订单不存在');
                exit;
            }

            // 先获取物流单号
            $code = empty($order['expresscode']) ? '' : $order['expresscode'];

            if (empty($code)) {
                $this->error('快递单号为空，无法查询物流');
                exit;
            }

            // 调用物流接口
            $url = "https://wuliu.market.alicloudapi.com/kdi?no=$code"; //api访问链接

            // 请求信息
            $appcode = "6c5d6f10546c41939ec96b74c935e661";
            $headers = array();
            array_push($headers, "Authorization:APPCODE " . $appcode);

            //初始化接口curl请求
            $curl = curl_init();

            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($curl, CURLOPT_FAILONERROR, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_HEADER, true);

            // https 请求的验证
            if (1 == strpos("$" . $url, "https://")) {
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            }

            // 执行发起请求
            $out_put = curl_exec($curl);

            // 获取结果信息
            $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

            list($header, $body) = explode("\r\n\r\n", $out_put, 2);

            if ($httpCode != 200) {
                $this->error('查询物流接口失败');
                exit;
            }

            $result = json_decode($body, true);

            $list = isset($result['result']['list']) ? $result['result']['list'] : [];
            $expName = isset($result['expName']) ? $result['expName'] : '';
            $courier = isset($result['courier']) ? $result['courier'] : '';
            $courierPhone = isset($result['courierPhone']) ? $result['courierPhone'] : '';


            // 组装数据
            $data = [
                'list' => $list,
                'expName' => $expName,
                'courier' => $courier,
                'courierPhone' => $courierPhone,
            ];

            if (empty($list)) {
                $this->error('未查询到物流记录');
                exit;
            } else {
                $this->success('查询物流信息成功', null, $data);
                exit;
            }
        }
    }

    //确认收货
    public function confirm()
    {
        if ($this->request->isPost()) {
            $orderid = $this->request->param('orderid', 0, 'trim');

            $where = [
                'busid' => $this->business->id,
                'id' => $orderid
            ];
            $order = $this->OrderModel->where($where)->find();
            if (!$order) {
                $this->error('订单不存在');
                exit;
            }

            // 组装数据
            $data = [
                'id' => $orderid,
                'status' => '3'
            ];

            $result = $this->OrderModel->isUpdate(true)->save($data);
            if ($result === false) {
                $this->error('确认收货失败');
                exit;
            } else {
                $this->success('确认收货成功');
                exit;
            }
        }
    }

    // 退货
    public function back()
    {
        if ($this->request->isPost()) {
            $orderid = $this->request->param('orderid', 0, 'trim');
            $action = $this->request->param('action', '', 'trim');

            $where = [
                'busid' => $this->business->id,
                'orderid' => $orderid,
            ];

            // 判断订单是否存在
            $OrderProduct = $this->OrderProductModel->with(['order', 'products'])->where($where)->select();
            if (!$OrderProduct) {
                $this->error('订单商品不存在');
                exit;
            }
            // halt(collection($OrderProduct)->toArray());
            // exit;

            // 加载模型
            $ProductModel = model('Product.Product');
            $BusinessModel = model('Business.Business');
            $OrderModel = model('Order.Order');
            $BackModel = model('Depot.Back');
            $BackProductModel = model('Depot.BackProduct');



            // 退款处理
            // 更新product库存stock
            // 更新business余额money
            // 更新订单表status '-1'
            if ($action == 'onlymoney') {
                // 开启事务
                $ProductModel->startTrans();
                $BusinessModel->startTrans();
                $OrderModel->startTrans();

                $ProductData = [];
                // 库存更新
                foreach ($OrderProduct as $item) {
                    $stock = $item['products']['stock'];
                    $nums = $item['pronum'];
                    $UpdateStock = bcadd($stock, $nums);
                    $ProductData[] = [
                        'id' => $item['products']['id'],
                        'stock' => $UpdateStock,
                    ];
                }

                // 更新商品表数据
                // $ProductData=[

                // ];

                $ProductStatus = $ProductModel->isUpdate(true)->saveAll($ProductData);
                if ($ProductStatus === FALSE) {
                    $this->error('更新商品库存失败');
                    exit;
                }

                // 余额更新
                $money = $this->business->money;
                $total = $OrderProduct[0]['order']['amount'];
                $UpdateMoney = bcadd($money, $total);

                // 更新用户余额数据
                $BusinessData = [
                    'id' => $this->business->id,
                    'money' => $UpdateMoney
                ];

                $BusinessStatus = $BusinessModel->isUpdate(true)->save($BusinessData);

                if ($BusinessStatus === FALSE) {
                    $ProductModel->rollback();
                    $this->error('更新用户余额失败');
                    exit;
                }

                // 更新订单状态
                $OrderData = [
                    'id' => $OrderProduct[0]['order']['id'],
                    'status' => '-1'
                ];
                $OrderStatus = $OrderModel->isUpdate(true)->save($OrderData);
                if ($OrderStatus === FALSE) {
                    $BusinessModel->rollback();
                    $ProductModel->rollback();
                    $this->error('更新订单状态失败');
                    exit;
                }
                if ($ProductStatus === FALSE || $BusinessStatus === FALSE || $OrderStatus === FALSE) {
                    $OrderModel->rollback();
                    $BusinessModel->rollback();
                    $ProductModel->rollback();
                    $this->error('退款失败，请联系客服');
                    exit;
                } else {
                    $ProductModel->commit();
                    $BusinessModel->commit();
                    $OrderModel->commit();
                    $this->success('退款成功');
                    exit;
                }
            }

            // 退款退货
            // 退货表 depot_back 插入
            // 退货商品表 depot_back_product 插入
            // 订单表 状态 -1
            if ($action == 'moneygoods') {
                // 查询收货地址信息
                $where = [
                    'busid' => $this->business->id,
                    'id' => $OrderProduct[0]['order']['businessaddrid'],
                ];

                $contact = $this->AddressModel->where($where)->find();
                // halt($contact->toArray());
                // exit;
                if (!$contact) {
                    $this->error('无联系人');
                    exit;
                }

                // 开启事务
                $BackModel->startTrans();
                $BackProductModel->startTrans();
                $OrderModel->startTrans();

                // 插入退货表数据
                $code = build_code('BP');
                $BackData = [
                    'code' => $code,
                    'ordercode' => $OrderProduct[0]['order']['code'],
                    'busid' => $this->business->id,
                    'contact' => $contact['consignee'],
                    'phone' => $contact['mobile'],
                    'address' => $contact['address'],
                    'province' => $contact['province'],
                    'city' => $contact['city'],
                    'district' => $contact['district'],
                    'amount' => $OrderProduct[0]['order']['amount'],
                    'status' => '0',
                ];
                // halt($BackData);
                // exit;

                $BackStatus = $BackModel->validate('common/Depot/Back')->save($BackData);
                if ($BackStatus === FALSE) {
                    $this->error($BackModel->getError());
                    exit;
                }

                //获取插入的新增订单ID
                $backid = $BackModel->id;

                // 退货商品表插入数据
                $BackProductData = [];
                foreach ($OrderProduct as $item) {
                    $BackProductData[] = [
                        'backid' => $backid,
                        'proid' => $item['proid'],
                        'nums' => $item['pronum'],
                        'price' => $item['price'],
                        'total' => $item['total']
                    ];
                }

                $BackProductStatus = $BackProductModel->validate('common/Depot/BackProduct')->saveAll($BackProductData);
                if ($BackProductStatus === FALSE) {
                    $BackModel->rollback();
                    $this->error($BackProductModel->getError());
                    exit;
                }

                // 更新订单表状态数据
                $OrderData = [
                    'id' => $orderid,
                    'status' => '-1',
                ];
                $OrderStatus = $OrderModel->isUpdate(true)->save($OrderData);
                if ($OrderStatus === FALSE) {
                    $BackProductModel->rollback();
                    $BackModel->rollback();
                    $this->error('更新订单状态失败');
                    exit;
                }

                if ($BackStatus === FALSE || $BackProductStatus === FALSE || $OrderStatus === FALSE) {
                    $OrderModel->rollback();
                    $BackProductModel->rollback();
                    $BackModel->rollback();
                    $this->error('退货退款失败，请联系客服');
                    exit;
                } else {
                    $BackModel->commit();
                    $BackProductModel->commit();
                    $OrderModel->commit();
                    $this->success('退款退货申请成功，请等待后台审核');
                    exit;
                }

            }


            // // 组装更新数据
            // $data=[
            //     'id'=>$orderid,
            //     'status'=>'-1'
            // ];
            // $result=$this->OrderModel->isUpdate(true)->save($data);
            // if($result===FALSE)
            // {
            //     $this->error('更新订单状态失败');
            //     exit;
            // }else
            // {
            //     $this->success('退货成功',null,$result);
            //     exit;
            // }
        }
    }

    // 查询快递信息
    public function expressAll()
    {
        $express=$this->ExpressqueryModel->select();
        if($express)
        {
            $this->success('返回快递信息',null,$express);
        }
    }

    /**
     * 填写退货物流，更新退货表数据
    */ 
    public function backwuliu()
    {
        if($this->request->isAjax())
        {
            $express=$this->request->param('express','','trim');
            $expresscode=$this->request->param('expresscode','','trim');
            $backid=$this->request->param('backid','','trim');
            // halt($backid);
            $expressid=$this->ExpressqueryModel->where(['name' => ['LIKE', "%$express%"]])->value('id');
            // halt($expressData);
            // 组装数据
            $data=[
                'id'=>$backid,
                "expressid"=>$expressid,
                "expresscode"=>$expresscode,
            ];
            $result=$this->BackModel->isUpdate(true)->save($data);
            if($result===false)
            {
                $this->error('填写退货物流失败');
                exit;
            }else
            {
                $this->success('填写退货物流成功');
                exit;
            }
        }
    }
}